package com.example.game_app.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.example.game_app.R;
import com.example.game_app.adapter.StarListAdapter;
import com.example.game_app.util.Request;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameStarViewFragment extends Fragment {
    // 明星列表视图
    ListView listView;
    // 明星元素集合
    List<Map<String, String>> starList = new ArrayList<>();
    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件并返回视图
        return inflater.inflate(R.layout.game_star_view, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里初始化视图和设置监听器等操作
        listView = view.findViewById(R.id.starLists);
        getStarList(view);
    }

    // 发起请求获取明星数据
    private void getStarList(View view) {
        new Thread() {
            public void run() {
                Request request = new Request();
                String result = request.get("/stars/list");
                getJsonArray(result,starList);
            }
        }.start();
    }

    // 解析JSON数据为map，并进行适配器数据映射
    private void getJsonArray(String result, List<Map<String, String>> starList) {
        try{
            JSONArray jsonArray = new JSONArray(result);
            starList.clear();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String starName = jsonObject.getString("starName");
                String starIntroduction = jsonObject.getString("starIntroduction");
                String starImage = jsonObject.getString("starImage");
                HashMap<String, String> map = new HashMap<>();
                map.put("starName",starName);
                map.put("starIntroduction",starIntroduction);
                map.put("starImage",starImage);
                starList.add(map);
            }
        //     异步数据映射
            mHandler.post(() -> listView.setAdapter(new StarListAdapter(requireContext(),starList)));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}
